package com.bigtotoro.shuiyincamera.util;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.Constant;
import com.bigtotoro.shuiyincamera.MyApplication;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.SettingActivity;
import com.bigtotoro.shuiyincamera.model.BaseResponse;
import com.bigtotoro.shuiyincamera.model.VersionDetails;
import com.bigtotoro.shuiyincamera.model.VersionInfo;
import com.bigtotoro.shuiyincamera.model.VersionResponse;
import com.google.gson.Gson;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.statistics.common.DeviceConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import iknow.android.utils.BaseUtils;

import static android.provider.Settings.System.getString;
import static com.luck.picture.lib.tools.PictureFileUtils.deleteFile;


/**
 * auther: Administrator.
 * Date: 2019/4/27.
 */

public class MyUtils {

    public static void addUmengEvent(Activity activity, String eventId, String desc) {
        Map<String, Object> event = new HashMap<String, Object>();
        event.put("action_type", desc);//自定义参数：音乐类型，值：流行
        MobclickAgent.onEventObject(activity, eventId, event);
    }


    public static String[] getTestDeviceInfo(Context context) {
        String[] deviceInfo = new String[2];
        try {
            if (context != null) {
                deviceInfo[0] = DeviceConfig.getDeviceIdForGeneral(context);
                deviceInfo[1] = DeviceConfig.getMac(context);
                Log.i("设备信息", "deviceId = " + deviceInfo[0] + ",mac==" + deviceInfo[1]);
            }
        } catch (Exception e) {
        }
        return deviceInfo;
    }

    public static void DeleteFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
        } else {
            if (file.isFile()) {
                // 为文件时调用删除文件方法
                deleteFile(filePath);
            } else {
                // 为目录时调用删除目录方法
            }
        }
    }

    public void deleteLocal(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();//如果为文件，直接删除
            }
//            else if(file.isDirectory()){
//                File []files=file.listFiles();
//                for(File file1:files){
//                    deleteLocal(file1);//如果为文件夹，递归调用
//                }
//            }
            file.delete();
        }
    }

    public interface StrCallback {
        void callback(String str, int isNew);

    }

    public static boolean isSpecialChar(String str) { //判断非法字符
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    public static void checkOrcopyFile(String oldPath$Name, StrCallback callback) {
        int isZhongwen = -1;
        if (oldPath$Name != null && oldPath$Name.length() > 0) {
            for (int i = 0; i < oldPath$Name.length(); i++) {
                if (oldPath$Name.charAt(i) > 127) { //包含中文
                    isZhongwen = 1;
                } else {

                }
            }
            if (isSpecialChar(oldPath$Name)) { //包含特殊字符
                isZhongwen = 1;
            } else {

            }

        }

        if (isZhongwen > 0) {
            try {
                File oldFile = new File(oldPath$Name);
                if (!oldFile.exists()) {
                    Log.e("--Method--", "copyFile:  oldFile not exist.");
                    callback.callback(oldPath$Name, -1);
                } else if (!oldFile.isFile()) {
                    Log.e("--Method--", "copyFile:  oldFile not file.");
                    callback.callback(oldPath$Name, -1);
                } else if (!oldFile.canRead()) {
                    Log.e("--Method--", "copyFile:  oldFile cannot read.");
                    callback.callback(oldPath$Name, -1);
                }

                String newPath$Name = VideoUtil.VIDEO_OUT_DIR + "/" + System.currentTimeMillis() + ".mp3";
                FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
                FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
                byte[] buffer = new byte[1024];
                int byteRead;
                while (-1 != (byteRead = fileInputStream.read(buffer))) {
                    fileOutputStream.write(buffer, 0, byteRead);
                }
                fileInputStream.close();
                fileOutputStream.flush();
                fileOutputStream.close();
                Log.i("--Method--", "包含非法字符或中文");
                callback.callback(newPath$Name, 1);
            } catch (Exception e) {
                e.printStackTrace();
                callback.callback(oldPath$Name, -1);
            }

        } else {
            callback.callback(oldPath$Name, -1);
        }


    }


    /**
     * 版本号比较
     * 0代表相等，1代表version1大于version2，-1代表version1小于version2
     *
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        Log.d("HomePageActivity", "version1Array==" + version1Array.length);
        Log.d("HomePageActivity", "version2Array==" + version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        Log.d("HomePageActivity", "verTag2=2222=" + version1Array[index]);
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    public interface VersionInfoCallback {
        void callback(VersionInfo data);
    }

    public static void checkVersion(Activity activity, int isShowToast, IntegerCallback callback) {

        String currentVersion = SystemUtils.getVersion();
        OkGo.<String>get(Constant.API + "app/check_version?app=dakacamera").tag(activity)
                .headers("Content-Type", "application/x-www-form-urlencoded")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        BaseResponse base = new Gson().fromJson(response.body(), BaseResponse.class);
                        if (base.getCode() == 0) {
                            VersionResponse versionResponse = new Gson().fromJson(response.body(), VersionResponse.class);
                            if (versionResponse != null && versionResponse.getData() != null) {
                                VersionDetails versionDetails = versionResponse.getData();
                                String onlineVersion = versionDetails.getVersion();
                                int result = compareVersion(onlineVersion, currentVersion);
                                if (result > 0) {
                                    callback.callback(2);  //有新版本
                                    if (isShowToast > 0) {
                                        Toast.makeText(activity, R.string.version02 + "v" + versionDetails.getVersion(), Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    callback.callback(-2);
                                    if (isShowToast > 0) {
                                        Toast.makeText(activity, R.string.version01, Toast.LENGTH_SHORT).show();
                                    }
                                }

//                                if (onlineVersion > currentVersion){ //如果低于线上版本
//                                    callback.callback(2);  //有新版本
//                                    if (isShowToast > 0){
//                                    Toast.makeText(activity, R.string.version02+"v"+versionDetails.getVersion(), Toast.LENGTH_SHORT).show();
//                                    }
//                                }else {
//                                    callback.callback(-2);
//                                    if (isShowToast>0){
//                                    Toast.makeText(activity, R.string.version01, Toast.LENGTH_SHORT).show();
//                                    }
//                                }
                            }
                        } else {
                            callback.callback(-1);
                            if (isShowToast > 0) {
                                Toast.makeText(activity, "" + base.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        if (isShowToast > 0) {
                            Toast.makeText(activity, R.string.error_500, Toast.LENGTH_SHORT).show();
                        }
                        callback.callback(-1);
                    }
                });


    }


    /**
     * 分享前必须执行本代码，主要用于兼容SDK18以上的系统
     * 否则会报android.os.FileUriExposedException: file:///xxx.pdf exposed beyond app through ClipData.Item.getUri()
     */
    public static void checkFileUriExposure() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    }

    public static void shareMultiplePictureToTimeLine(Context context,String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            Toast.makeText(context, "文件不存在，请重新选择", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(filePath);
        checkFileUriExposure();

        Uri localUri1 =  getImageContentUri(context,file);
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.putExtra("android.intent.extra.TEXT", "大咖水印相机");
        localIntent.putExtra("sms_body", "大咖水印相机");
        localIntent.putExtra("Kdescription", "大咖水印相机");
        if (localUri1 == null)
            return;
        localIntent.putExtra("android.intent.extra.STREAM", localUri1);
//        localIntent.setType("*/*");
//        localIntent.setType("image/*");
//        localIntent.setType("video/*");
        localIntent.setType("audio/*");
        context.startActivity(Intent.createChooser(localIntent, "Share"));
    }


    /**
     * 调用系统应用打开文件（系统分享）
     *
     * @param context
     * @param filePath 文件路径
     */
    public static void shareToThirdApp(Context context, String filePath,String type) {
        if (TextUtils.isEmpty(filePath)) {
            Toast.makeText(context, "文件不存在，请重新选择", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(filePath);
        checkFileUriExposure();

//       Uri uri =  getImageContentUri(context,file);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
//        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra("Kdescription", "大咖水印相机");
        if (type!=null && type.equals("0")){
            intent.setType("image/*");
        }else if (type!=null && type.equals("1")){
            intent.setType("video/*");
        }else if (type!=null && type.equals("2")){
            intent.setType("audio/*");
        }

//        intent.setType("*/*");   //分享文件类型

        context.startActivity(Intent.createChooser(intent, R.string.menu_share + ""));
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        Uri uri = null;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }
            cursor.close();
        }
        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }
        return uri;
    }

    //获取底部导航栏的高度
    public static int getNavigationBarHeight(Activity activity) {
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        Log.v("dbw", "Navi height:" + height);
        return height;
    }

    public static boolean checkDeviceHasNavigationBar(Activity activity) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        if (!hasMenuKey && !hasBackKey) {
            // 没有虚拟按键返回 true
            return true;
        }
        // 有虚拟按键返回 false
        return false;
    }


    //获取指定控件高度或宽度//isheight=true为获取高度，false为获取宽度
    public static int getViewHeight(View view, boolean isHeight) {
        int result;
        if (view == null) return 0;
        if (isHeight) {
            int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(h, 0);
            result = view.getMeasuredHeight();
        } else {
            int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(0, w);
            result = view.getMeasuredWidth();
        }
        return result;
    }

    /**
     * TODO 除法运算，保留小数
     *
     * @param denominator 被除数 分子
     * @param numerator   除数 分母
     * @return 商
     */
    public static float toFloat(int denominator, int numerator) {
        // TODO 自动生成的方法存根
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        return Float.valueOf(df.format((float) denominator / numerator));
    }

    public static float toFloat(int denominator, float numerator) {
        // TODO 自动生成的方法存根
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        return Float.valueOf(df.format((float) denominator / numerator));
    }

    /**
     * 获取视频文件截图
     *
     * @param path 视频文件的路径
     * @return Bitmap 返回获取的Bitmap
     */

    public static Bitmap getVideoThumb(String path) {

        MediaMetadataRetriever media = new MediaMetadataRetriever();

        media.setDataSource(path);

        return media.getFrameAtTime();

    }

    public static int dp2px(int values) {
        float scale = MyApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (values * scale + 0.5f);
    }

    public static int px2dip(float pxValue) {
        float scale = MyApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int px2sp(float pxValue) {
        float fontScale = MyApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public static int sp2px(float spValue) {
        final float fontScale = MyApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static void createViewBitmap(View v, int widtg, int height, BitmapCallback callback) {
        Bitmap bitmap = Bitmap.createBitmap(widtg, height,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        callback.callback(bitmap);
    }

    public static void createViewBitmap(View v, BitmapCallback callback) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        callback.callback(bitmap);
    }


    public interface BitmapCallback {
        void callback(Bitmap data);
    }


    public static void checkReadAndWritePermission(Activity activity, IntegerCallback callback) {
        new RxPermissions(activity)
                .request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        callback.callback(1);
                    } else {
                        callback.callback(-1);
                        Toast.makeText(activity, R.string.warning02, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public interface IntegerCallback {
        void callback(int data);
    }


}
